require "raspell"

class CheckResult < ActionWebService::Struct
  include Reloadable

  member :input_text, :string
  member :incorrect_words, [:string]
  member :suggestions, [[:string]]

  attr_reader :input_text, :incorrect_words, :suggestions

  def self.check_multi_inputs(inputs)
    inputs.map do |input|
      CheckResult.new(input)
    end
  end

  def self.to_js(check_results)
    result = <<EOF
var suggs = new Array();
var words = new Array();
var textinputs = new Array();
EOF
    check_results.each do |check_result|
      index = check_results.index(check_result)
      result << check_result.to_js(index)
    end
    result
  end

  def initialize(input_text)
    @input_text = CGI::unescape(input_text)
    check_spell
  end
  
  def to_js(index_in_results)
    result = <<EOF
textinputs[#{index_in_results}] = '#{@input_text}'
words[#{index_in_results}] = [];
suggs[#{index_in_results}] = [];
EOF
    @incorrect_words.each do |word|
      index = @incorrect_words.index(word)
      result << "words[#{index_in_results}][#{index}] = '#{word}';\n"
      result << "suggs[#{index_in_results}][#{index}] = #{@suggestions[index].inspect};\n"
    end
    result
  end
  
  private
  def check_spell
    aspell = Aspell.new("en_US")
    @incorrect_words = aspell.list_misspelled([@input_text])
    @suggestions = @incorrect_words.map do |word|
      aspell.suggest(word)
    end
  end
end